/**
 * ...
 * @author Krzysztof Rozalski
 */

package hapi.sprite.blit.canvas;

import flash.events.Event;
import haxe.FastList;
import haxe.Timer;

class BlitCanvasBase implements BlitCanvas {

	static var initialized:Bool = false;
	static var canvases:FastList<BlitCanvasBase> = new FastList<BlitCanvasBase>();
	
	var needRefresh:Bool;
	var frameDuration:Float;
	var refreshStamp:Float;
	var fps:Float;
	public var width(default, null):Int;
	public var height(default, null):Int;
	public var frameRate(getFrameRate, setFrameRate):Float;
	
	function new(width:Int, height:Int, ?frameRate:Null<Float>) {
		this.width = width;
		this.height = height;
		if (frameRate == null) frameRate = flash.Lib.current.stage.frameRate;
		this.needRefresh = true;
		frameDuration = 1 / frameRate;
		refreshStamp = -frameDuration;
		stopRefreshing();
		if (!initialized) {
			flash.Lib.current.stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
			initialized = true;
		}
		canvases.add(this);
	}
	
	static function onEnterFrame(event:Event) {
		updateCanvases();
	}
	
	public static inline function updateCanvases():Void {
		var now:Float = Timer.stamp();
		for ( c in canvases ) { 
			if (c.needRefresh && now > c.refreshStamp) c.refresh();
		}
	}
	
	public function keepRefreshing() {
		needRefresh = true;
	}
	
	public function stopRefreshing() {
		needRefresh = false;
	}
	
	public function refresh():Void {
		refreshStamp = Timer.stamp() + frameDuration;
	}
	
	function getFrameRate():Float {
		return this.fps;
	}
	
	function setFrameRate(frameRate:Float):Float {
		if(frameRate > 0 ) {
			this.fps = frameRate;
			var lastRefresh = refreshStamp - frameDuration;
			frameDuration = 1 / frameRate;
			refreshStamp = lastRefresh + frameDuration;
		}
		return fps;
	}
}